﻿using DataRepositoryLayer.Interfaces;
using ModelLayer;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DataRepositoryLayer.Classes
{
    public class EmployeeAccountRepository : GenericDataRepository<EmployeeAccount>, IEmployeeAccountRepository
    {

        public EmployeeAccountRepository(IUnitOfWork unitOfWork)
            : base(unitOfWork)
        {

        }

        public EmployeeAccount CheckSessionToken(string token)
        {
            if(IsGoodToken(token))
            {
                return GetSingle(ea => ea.session_token == token, a => a.Station.Batteries, acc => acc.Station.Pricings);
            }
            return null;
        }

        public EmployeeAccount GetByUsername(string username)
        {
            return GetSingle(ea => ea.username == username, a => a.Station.Batteries, acc => acc.Station.Pricings);
        }

        public IList<EmployeeAccount> GetAllAccountsForManagementSystem()
        {
            return GetAll(ea => ea.Station);
        }

        private bool IsGoodToken(string token)
        {
            long ticks = 0;
                
            if (token == null || token.Length < 11 || !long.TryParse(token.Substring(10), out ticks))
            {
                return false;
            }
            return DateTime.Now.Ticks - ticks < (long)10000 * 1000 * 60 * 60 * 8;
        }


        public EmployeeAccount GetById(int id)
        {
            return GetSingle(ea => ea.id == id);
        }
    }
}
